<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    :mask-closable="false"
    :bordered="false"
    :style="{ width: '800px' }"
    class="custom-card"
    preset="card"
  >
    <x-form ref="formRef" v-model:model="form" inline wrap label-placement="left">
      <div>
        <n-radio-group v-model:value="form.exportType">
          <n-radio-button :value="0">部分导入</n-radio-button>
          <n-radio-button :value="1">全部导入</n-radio-button>
        </n-radio-group>
      </div>
      <template v-if="form.exportType === 0">
        <div style="width: 100%; margin: 8px 0">
          <n-radio-group v-model:value="form.changeType">
            <n-radio :value="0">手动输入</n-radio>
            <n-radio :value="1">手动选择</n-radio>
          </n-radio-group>
        </div>
        <n-alert v-if="form.changeType === 0" type="warning">
          请确保输入的广告主账户已属于对应的代理商，否则会导致失败;单次授权账户上限300个，如账户数量较多请分批次输入
        </n-alert>
        <n-alert v-if="form.changeType === 1" type="warning">
          该商务管家下共{{ tableTotal }}个媒体账户，请选择想要导入的账户名称
        </n-alert>
        <div v-if="form.changeType === 0" class="ad-content">
          <div class="ad-content-title">
            请输入广告主账户ID（{{ listText.length }}/300）
            <x-button type="primary" text style="float: right" @click="handleDeleteList">清空</x-button>
          </div>
          <n-alert :show-icon="false"> 请输入广告主账户ID，多账户请换行（即每个账户ID一行） </n-alert>
          <div class="input-list">
            <div class="input-list-container">
              <div class="serial">
                <div v-for="(item, index) in listText" :key="index" :class="['plaid', item.error ? 'active' : '']">{{
                  index + 1
                }}</div>
              </div>
              <div class="content">
                <div class="input-group">
                  <n-input
                    v-for="(item, index) in listText"
                    :key="index"
                    v-model:value="item.value"
                    type="text"
                    :show-button="false"
                    style="border: none"
                    placeholder="请粘贴或输入广告主账户ID，回车可换行"
                    rows="10"
                    maxlength="30"
                    @input="filterInput($event, index)"
                    @keyup.enter="pushList"
                    @paste="pushListV($event, index)"
                    @mouseenter="handleEnter(index)"
                    @mouseleave="handleLeave"
                  >
                    <template #suffix>
                      <x-button v-if="activeIndex === index" text class="deleteIcon" @click="handleDeleteItem(index)"
                        >X</x-button
                      >
                    </template>
                  </n-input>
                </div>
              </div>
            </div>
          </div>
          <div class="error-list">
            <span v-if="isErrorList">输入广告主账户ID的存在重复</span>
            <span v-for="(item, index) in listText" :key="index">
              <n-text v-if="item.error" type="error" style="margin-right: 4px">第{{ index + 1 }}行</n-text>
            </span>
          </div>
        </div>
      </template>
      <template v-if="form.changeType === 1 || form.exportType === 1">
        <div style="width: 100%; margin-top: 8px">
          <n-alert v-if="form.exportType === 1" type="warning">
            该商务管家下共{{ tableTotal }}个媒体账户，请选择想要导入的账户名称
          </n-alert>
        </div>
        <div style="margin-top: 8px">
          <x-form ref="formRef1" v-model:model="form1" inline label-placement="left">
            <n-form-item label="账户ID">
              <n-input v-model:value="form1.accountCode" type="text" />
            </n-form-item>
            <n-form-item label="账户名称">
              <n-input v-model:value="form1.accountName" type="text" />
            </n-form-item>
            <x-button type="primary" @click="getData(1, '')">查询</x-button>
          </x-form>
        </div>
        <div>
          <n-data-table
            ref="tableRef"
            v-model:checked-row-keys="checkedRowKeys"
            :data="tableData"
            :params="paginationParams"
            :columns="columns"
            :row-key="(row) => row.accountCode"
            :is-reload="false"
            row-class-name="text-sm"
            max-height="infinite"
          />
          <div class="flex" style="float: right; margin-top: 10px">
            <x-button :disabled="pageInfo.pageNum < 2 || loading" @click="prevPage">上一页</x-button>
            <n-select
              v-model:value="pageSize"
              style="width: 50px; margin: 0 8px"
              :options="pageSizeOption"
              @update:value="getData(1, '')"
            />
            <x-button :disabled="!hasMore || loading" @click="nextPage">下一页</x-button>
          </div>
        </div>
      </template>
    </x-form>
    <template #footer>
      <n-space justify="end">
        <x-form ref="formRef2" v-model:model="form2" :rules="rules" inline label-placement="left">
          <n-form-item label="所属人员" path="accountId">
            <n-select
              v-model:value="form2.accountId"
              :options="getProps.accountList"
              value-field="accountId"
              label-field="accountName"
              filterable
              clearable
            />
          </n-form-item>
        </x-form>
        <x-button @click="handleCancel">取消</x-button>
        <x-button :disabled="loading" :loading="loading" type="primary" @click="handleConfirm()">确认</x-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
  import { XButton, XForm } from '@/components'
  import {
    NModal,
    NSpace,
    NRadioGroup,
    NRadio,
    NRadioButton,
    NAlert,
    NInput,
    NInputNumber,
    NFormItem,
    NText,
    NDataTable,
    NSelect,
    useMessage
  } from 'naive-ui'
  import { v4 as uuidv4 } from 'uuid'
  import { computed, onMounted, reactive, ref, watch } from 'vue'
  import { useStore } from '@/store'
  import { useRouter } from 'vue-router'
  const store = useStore()
  const router = useRouter()
  const emits = defineEmits(['success'])
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    },
    accountList: {
      type: Array,
      default: () => []
    }
  })
  const message = useMessage()
  const getProps = reactive(props)
  const formRef = ref(null)
  const form = ref({
    exportType: 0,
    changeType: 0,
    list: ''
  })
  const listText = ref([
    {
      value: null,
      index: 0,
      error: null
    }
  ])
  const activeIndex = ref(-1)
  const formRef1 = ref(null)
  const form1 = ref({
    accountCode: null,
    accountName: null
  })
  const formRef2 = ref(null)
  const form2 = ref({
    accountId: null
  })
  const rules = reactive({
    accountId: { required: true, type: 'number', message: '请选择所属人员', trigger: 'blur' }
  })
  const uuid = ref(uuidv4())
  const tableData = ref([])
  const tableTotal = ref(0)
  const immediate = ref(false)
  const loading = ref(false)
  const paginationParams = computed(() => {
    return {
      actions: 'system/mediaAccountMediaList',
      data: {
        ...form1.value,
        id: getProps.modalData.id
      }
    }
  })
  const isErrorList = computed(() => {
    return listText.value.findIndex((item) => item.error) > -1
  })
  const checkedRowKeys = ref([])

  const columns = ref([
    {
      type: 'selection',
      disabled() {
        return form.value.exportType === 1
      }
    },
    {
      title: '账户名称',
      key: 'accountName'
    },
    {
      title: '账户ID',
      key: 'accountCode'
    },
    {
      title: '所属人员',
      key: 'ownerName'
    }
  ])

  const newList = ref([])
  watch(
    listText.value,
    (val) => {
      findAndModifyDuplicates(val, 'value')
    },
    { deep: true, immediate: true }
  )
  function findAndModifyDuplicates(arr: any[], key: string) {
    // const valueMap = new Map()
    // const valueList = arr.map((item) => item.value)
    //
    // arr.forEach((item, index) => {
    //   const val = item[key]
    //   console.log(val, 11111, valueMap)
    //   if (valueMap.has(val)) {
    //     arr[index].error = 'error'
    //     const originalIndex = valueMap.get(val)
    //     arr[originalIndex].error = 'error'
    //   } else {
    //     arr[index].error = null
    //     valueMap.set(val, index)
    //   }
    // })
    //
    // return arr
    const count = {}
    const result = arr.map((item) => ({ ...item }))
    // First pass to count occurrences
    result.forEach((item) => {
      count[item[key]] = (count[item[key]] || 0) + 1
    })

    // Second pass to update error field
    result.forEach((item) => {
      if (count[item[key]] > 1) {
        item.error = 'error'
      } else {
        item.error = ''
      }
    })
    listText.value = result

    return result
  }

  const pageSize = ref(10)
  const cursor = ref(null)
  const hasMore = ref(true)
  const pageSizeOption = ref([
    {
      label: '10条/页',
      value: 10
    },
    {
      label: '20条/页',
      value: 20
    },
    {
      label: '30条/页',
      value: 30
    },
    {
      label: '50条/页',
      value: 50
    },
    {
      label: '100条/页',
      value: 100
    }
  ])
  onMounted(() => {
    getData(0, '')
  })

  const pageInfo = ref({
    prev: null,
    pageNum: 1
  })
  function prevPage() {
    getData(0, 'prev')
  }
  function nextPage() {
    getData(0, 'next')
  }

  function getData(pageNumber: number, type: string) {
    if (pageNumber) {
      cursor.value = null
      pageInfo.value = {
        prev: null,
        pageNum: 1
      }
      uuid.value = uuidv4()
      checkedRowKeys.value = []
    }
    if (type === 'prev') {
      pageInfo.value.pageNum--
    } else if (type === 'next') {
      pageInfo.value.pageNum++
    }
    if (pageInfo.value.pageNum < 1) {
      return
    }
    loading.value = true
    store
      .dispatch('system/mediaAccountMediaList', {
        id: getProps.modalData.id,
        ...form1.value,
        pageSize: pageSize.value,
        pageNum: pageInfo.value.pageNum,
        cursor: type === 'prev' ? pageInfo.value.prev : cursor.value,
        uuid: uuid.value
      })
      .then((res) => {
        tableData.value = res.data
        tableTotal.value = res.pageInfo?.total
        cursor.value = res.pageInfo?.cursor || null
        hasMore.value = res.pageInfo?.hasMore
        pageInfo.value.prev = res.pageInfo?.prev || null
        loading.value = false
      })
  }

  function handleDeleteList() {
    listText.value = [
      {
        value: null,
        index: 0,
        error: null
      }
    ]
  }
  const filterInput = (event, index) => {
    listText.value[index].value = event.replace(/[^0-9]/g, '').trim()
    findAndModifyDuplicates(listText.value, 'value')
  }
  function pushList() {
    listText.value.push({
      value: null,
      index: listText.value.length,
      error: null
    })
  }
  function pushListV(event: any, index) {
    event.preventDefault()
    const clipboardData = event.clipboardData || window.clipboardData
    const pastedData = clipboardData.getData('Text').trim()
    console.log(pastedData, index, 111)
    pastedData.split('\n').forEach((item) => {
      item.split(' ').forEach((item1) => {
        if (!Number.isNaN(+item1) && item1) {
          if (!listText.value[index].value) {
            listText.value[index].value = item1
          } else {
            listText.value.push({
              value: item1,
              index: listText.value.length,
              error: null
            })
          }
        }
      })
    })
    findAndModifyDuplicates(listText.value, 'value')
    //
    // if (pastedData) {
    //   if (!Number.isNaN(+pastedData)) {
    //     listText.value.push({
    //       value: pastedData,
    //       index: listText.value.length,
    //       error: null
    //     })
    //     findAndModifyDuplicates(listText.value, 'value')
    //   }
    // }
  }
  function handleEnter(index: number) {
    activeIndex.value = index
  }
  function handleLeave() {
    activeIndex.value = -1
  }
  function handleDeleteItem(index: number) {
    if (listText.value.length === 1) {
      return
    }
    listText.value.splice(index, 1)
    findAndModifyDuplicates(listText.value, 'value')
  }

  const handleRefresh = () => {
    checkedRowKeys.value = []
    formRef1.value.resetFields()
    handleSubmit()
  }
  function handleSubmit() {
    immediate.value = true
  }

  async function handleConfirm() {
    formRef2.value.validate(async (errors: any) => {
      if (!errors) {
        let list = []
        listText.value.forEach((item) => {
          if (item.value) {
            list.push(item.value)
          }
        })
        if (form.value.changeType === 1) {
          list = checkedRowKeys.value
        }
        if (form.value.changeType === 0 && form.value.exportType === 0) {
          if (isErrorList.value) {
            return
          }
        }
        if (form.value.exportType === 0) {
          if (list.length === 0) {
            return message.warning('请输入广告主账户ID', { duration: 5000, keepAliveOnHover: true, closable: true })
          }
        } else {
          if (tableData.value?.length === 0) {
            return message.warning('暂无可导入账户')
          }
        }
        loading.value = true
        store
          .dispatch('system/mediaAccountBatchExport', {
            id: getProps.modalData.id,
            exportType: form.value.exportType,
            list: form.value.exportType === 0 ? list : null,
            accountCode: form1.value.accountCode,
            accountName: form1.value.accountName,
            accountId: form2.value.accountId,
            uuid: uuid.value
          })
          .then((res) => {
            const { data, success } = res
            loading.value = false

            if (success) {
              message.success(data, { duration: 5000, keepAliveOnHover: true, closable: true })
              getProps.modalData.show = false
              emits('success')
            } else {
              router.push({
                name: 'AdvCallback',
                query: {
                  uuid: uuid.value,
                  type: 1
                }
              })
              // message.warning(data, { duration: 5000, keepAliveOnHover: true, closable: true })
            }
          })
          .catch(() => {
            router.push({
              name: 'AdvCallback',
              query: {
                uuid: uuid.value,
                type: 1
              }
            })
          })
      }
    })
  }
  function handleCancel() {
    getProps.modalData.show = false
  }
</script>

<style scoped lang="scss">
  .ad-content {
    width: 100%;
    &-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 6px 0;
    }
  }
  .input-list {
    max-height: 300px;
    box-sizing: border-box;
    overflow-x: hidden;
    overflow-y: scroll;
    border: 1px solid #dadfe3;
    border-radius: 5px;
    &-container {
      display: flex;
      width: 100%;
      .serial {
        flex-shrink: 0;
        width: 36px;
        min-height: 400px;
        padding: 6px 0;
        vertical-align: middle;
        border-right: 1px solid #dadfe3;
        .plaid {
          box-sizing: border-box;
          display: inline-block;
          width: 100%;
          height: 34px;
          margin: 0 auto;
          line-height: 32px;
          text-align: center;
        }
        .active {
          background: red;
        }
      }
      .content {
        box-sizing: border-box;
        display: block;
        flex: 1;
        width: 100%;
        padding: 6px 12px;
        .input-group {
          position: relative;
          display: block;
        }
      }
    }
  }
</style>
